<template>
    <div>
      <Toolbar
        id="toobar"
        style="width:1128px; border: 1px solid #ddd;"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"/>
      <Editor
      id="edtior"
      style="height: 250px; overflow-y: auto; border: 1px solid #ddd;"
      v-model:modelValue="valueHtml"
      :defaultConfig="editorConfig"
      @onCreated="handleCreated"
      @onChange="handleChange"/>
    </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, watchEffect, watch } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { ElMessage } from 'element-plus';
import { IDomEditor } from '@wangeditor/editor';

// 声明属性-当父组件传递数据发生变化时触发
const props = defineProps<{ 
  modelValue: string
}>();
// 声明事件消息-当valueHtml发生变化时触发
const emit = defineEmits<(e: "update:modelValue", value: String) => void>();

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref('<p></p>');
// 监听父组件数据变化
watchEffect(() => {
  valueHtml.value = props.modelValue;
});

// 监听子组件数据变化
watch(valueHtml, (newHtml) => {
  emit("update:modelValue", newHtml);
});

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = props.modelValue;
    }, 1500);
});


// 工具配置
const toolbarConfig = {toolbarKeys: ["uploadImage"]};
const editorConfig = { 
  placeholder: '请输入Bug详情...',
  scroll: true,
  autoFocus: false,
  // 上传图片配置
  MENU_CONF: {
    uploadImage: {
      server: "/saferycom/file/upload_file",
      fieldName: "file",
      allowedFileTypes: ["image/*"],
      uploadImgMaxSize: 10 * 1024 * 1024, // 设置图片最大上传大小为10MB
      maxFileSize: 10 * 1024 * 1024, // 设置文件大小限制为10MB
      headers: {
        token: localStorage.getItem("TOKEN"),
      },
      customInsert: async (result: any, insertFn: any) => {
        console.log(result)
        if (result.code === 200) {
          insertFn(result.data.resultFilePath); //上传到服务器
        } else {
          ElMessage.error("上传图片失败");
          throw new Error();
        }
      },
    },
    customPaste: async (editor:any, event:any) => {
      const items = event.clipboarData.items;
      for (let item of items) {
        if(item.kind === 'file' && item.type.startsWith('image/')) {
          const file = item.getAsFile();
          const formData = new FormData();
          formData.append('file', file);
          fetch("/saferycom/file/upload_file", {
            method: "POST",
            body: formData,
          })
          .then(response => response.json())
          .then(result => {
            editor.cmd.do('insertHtml',`<img src="${result.resultFilePath}"/>`);
          })
          .catch(error => {
            ElMessage.error("粘贴图片上传失败",error);
            event.preventDefault();
          });
        }
      }
      event.preventDefault();
      return false;
    },
  },
};


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleChange = (editor: IDomEditor) => {
  const data = editor.getHtml();

  // 解析HTML字符串为DOM
  const parser = new DOMParser();
  const doc = parser.parseFromString(data, 'text/html');

  // 获取所有的img标签
  const images = doc.querySelectorAll('img');

  // 为每个img标签添加style属性
  images.forEach(img => {
    img.setAttribute('style', 'width: 30%;');
  });

  // 将修改后的DOM转换回字符串
  const modifiedData = doc.body.innerHTML;

  emit("update:modelValue", modifiedData);
};
</script> 
